'use strict';

// simple stub that could use a lot of work...
sdApp.factory('RESTService',
    function ($rootScope, $http, $q) {
        //configuration for this factory
        return {
            load: function (url) {
                var defer = $q.defer();
                $http({ method: 'GET', url: $rootScope.urlPrefix + url }).
                    success(function (data, status, headers, config) {
                        defer.resolve(data);                        
                    }).
                    error(function (data, status, headers, config) {
                        defer.resolve('error');
                    });
                return defer.promise;
            },
            get:function (url, callback) {
                return $http({method:'GET', url:url}).
                    success(function (data, status, headers, config) {
                        callback(data);
                        //console.log(data.json);
                    }).
                    error(function (data, status, headers, config) {
                        console.log("failed to retrieve data");
                    });
            }
        };
    }
);


sdApp.factory('APPService', function($rootScope, transformRequestAsFormPost, $q, $http, $state) {
    var APPService = {};
    APPService.registeerUser = function(data) {
        var dObj = $q.defer();
        $http({
            method: "post",
            transformRequest: transformRequestAsFormPost,
            url: $rootScope.urlPrefix + "/signup",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: data
        }).success(function(data) {
            dObj.resolve(data);
        }).error(function(err) {
            dObj.reject(err);
        });
        return dObj.promise;
    };
    APPService.authenticate = function(data) {
        var dObj = $q.defer();
        $http({
            method: "post",
            transformRequest: transformRequestAsFormPost,
            url: $rootScope.urlPrefix + "/authenticate",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: data
        }).success(function(data) {
            dObj.resolve(data);
        }).error(function(err) {
            dObj.reject(err);
        });;
        return dObj.promise;
    };
    APPService.logout = function(){
        $rootScope.restService.get($rootScope.urlPrefix + '/logout', function() {
            $rootScope.stateCard.userId = -1;
        });
    };
    return APPService;
});

sdApp.factory(
        "transformRequestAsFormPost",
        function() {

            // I prepare the request data for the form post.
            function transformRequest(data, getHeaders) {

                var headers = getHeaders();

                headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";

                return(serializeData(data));

            }


            // Return the factory value.
            return(transformRequest);


            // ---
            // PRVIATE METHODS.
            // ---


            // I serialize the given Object into a key-value pair string. This
            // method expects an object and will default to the toString() method.
            // --
            // NOTE: This is an atered version of the jQuery.param() method which
            // will serialize a data collection for Form posting.
            // --
            // https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
            function serializeData(data) {

                // If this is not an object, defer to native stringification.
                if (!angular.isObject(data)) {

                    return((data == null) ? "" : data.toString());

                }

                var buffer = [];

                // Serialize each key in the object.
                for (var name in data) {

                    if (!data.hasOwnProperty(name)) {

                        continue;

                    }

                    var value = data[ name ];

                    buffer.push(
                            encodeURIComponent(name) +
                            "=" +
                            encodeURIComponent((value == null) ? "" : value)
                            );

                }

                // Serialize the buffer and clean it up for transportation.
                var source = buffer
                        .join("&")
                        .replace(/%20/g, "+")
                        ;

                return(source);

            }

        }
);

sdApp.service('fillerDataSrv',function(){
    var topQuestions = {};
    var yourVotes = {};
    
    this.setTopQuestions = function(data){
        topQuestions = data;
    }
    this.topQuestions = function(){
        return topQuestions;
    }
    
    this.setYourVotes = function(data){
        yourVotes = data;
    }
    this.yourVotes = function(){
        return yourVotes;
    }
    
})